<template>
  <div class="ai-assistant-panel">
    <!-- AI助手工具栏 -->
    <div class="ai-toolbar">
      <el-dropdown @command="handleAICommand">
        <el-button type="primary" :icon="MagicStick">
          AI助手 <el-icon class="el-icon--right"><arrow-down /></el-icon>
        </el-button>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item command="meeting-summary" :icon="Document">
              生成会议总结
            </el-dropdown-item>
            <el-dropdown-item command="extract-tasks" :icon="List">
              提取任务
            </el-dropdown-item>
            <el-dropdown-item command="sales-script" :icon="ChatDotRound">
              销售话术建议
            </el-dropdown-item>
            <el-dropdown-item command="generate-content" :icon="Edit">
              内容生成
            </el-dropdown-item>
            <el-dropdown-item command="smart-search" :icon="Search">
              智能搜索
            </el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
    </div>

    <!-- 会议总结对话框 -->
    <el-dialog
      v-model="meetingSummaryDialogVisible"
      title="生成会议总结"
      width="500px"
    >
      <el-form :model="meetingSummaryForm" label-width="100px">
        <el-form-item label="开始时间">
          <el-date-picker
            v-model="meetingSummaryForm.startTime"
            type="datetime"
            placeholder="选择开始时间"
          />
        </el-form-item>
        <el-form-item label="结束时间">
          <el-date-picker
            v-model="meetingSummaryForm.endTime"
            type="datetime"
            placeholder="选择结束时间"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="meetingSummaryDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="generateMeetingSummary" :loading="generating">
          生成
        </el-button>
      </template>
    </el-dialog>

    <!-- 提取任务对话框 -->
    <el-dialog
      v-model="extractTasksDialogVisible"
      title="提取任务"
      width="600px"
    >
      <div class="task-extract-hint">
        <el-alert
          title="请选择包含任务信息的消息"
          type="info"
          :closable="false"
        />
      </div>
      <div class="message-selection">
        <el-checkbox-group v-model="selectedMessageIds">
          <div
            v-for="msg in recentMessages"
            :key="msg.id"
            class="message-checkbox-item"
          >
            <el-checkbox :label="msg.id">
              <div class="message-preview">
                <span class="sender">{{ msg.senderName }}:</span>
                <span class="content">{{ msg.content }}</span>
              </div>
            </el-checkbox>
          </div>
        </el-checkbox-group>
      </div>
      <template #footer>
        <el-button @click="extractTasksDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="extractTasks" :loading="generating">
          提取任务
        </el-button>
      </template>
    </el-dialog>

    <!-- 内容生成对话框 -->
    <el-dialog
      v-model="contentGenerateDialogVisible"
      title="AI内容生成"
      width="600px"
    >
      <el-form :model="contentGenerateForm" label-width="100px">
        <el-form-item label="内容类型">
          <el-select v-model="contentGenerateForm.contentType" placeholder="请选择">
            <el-option label="商品文案" value="PRODUCT_COPY" />
            <el-option label="营销文案" value="MARKETING_COPY" />
            <el-option label="活动方案" value="CAMPAIGN_PLAN" />
            <el-option label="邮件模板" value="EMAIL_TEMPLATE" />
          </el-select>
        </el-form-item>
        <el-form-item label="关键信息">
          <el-input
            v-model="contentGenerateForm.keywords"
            type="textarea"
            :rows="4"
            placeholder="请输入关键信息，如：产品名称、特点、目标客户等"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="contentGenerateDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="generateContent" :loading="generating">
          生成
        </el-button>
      </template>
    </el-dialog>

    <!-- 销售话术对话框 -->
    <el-dialog
      v-model="salesScriptDialogVisible"
      title="销售话术建议"
      width="600px"
    >
      <el-form :model="salesScriptForm" label-width="100px">
        <el-form-item label="客户ID">
          <el-input v-model="salesScriptForm.customerId" placeholder="请输入客户ID" />
        </el-form-item>
        <el-form-item label="当前阶段">
          <el-select v-model="salesScriptForm.stage" placeholder="请选择">
            <el-option label="初次接触" value="FIRST_CONTACT" />
            <el-option label="需求挖掘" value="NEED_DISCOVERY" />
            <el-option label="方案演示" value="DEMO" />
            <el-option label="谈判议价" value="NEGOTIATION" />
            <el-option label="促成签约" value="CLOSING" />
          </el-select>
        </el-form-item>
        <el-form-item label="补充信息">
          <el-input
            v-model="salesScriptForm.notes"
            type="textarea"
            :rows="3"
            placeholder="补充说明，如客户特点、痛点等"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="salesScriptDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="getSalesScript" :loading="generating">
          获取建议
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { MagicStick, Document, List, ChatDotRound, Edit, Search, ArrowDown } from '@element-plus/icons-vue'
import { aiMessageAPI } from '@/api/message'
import { useConversationStore } from '@/stores/conversation'
import type { Message } from '@/api/message'

const conversationStore = useConversationStore()

const generating = ref(false)

// 会议总结
const meetingSummaryDialogVisible = ref(false)
const meetingSummaryForm = ref({
  startTime: new Date(Date.now() - 3600000), // 默认1小时前
  endTime: new Date()
})

// 任务提取
const extractTasksDialogVisible = ref(false)
const selectedMessageIds = ref<string[]>([])

const recentMessages = computed(() => {
  const conversationId = conversationStore.activeConversationId
  if (!conversationId) return []
  
  const messages = conversationStore.messages.get(conversationId) || []
  return messages.slice(0, 20) // 最近20条消息
})

// 内容生成
const contentGenerateDialogVisible = ref(false)
const contentGenerateForm = ref({
  contentType: 'PRODUCT_COPY',
  keywords: ''
})

// 销售话术
const salesScriptDialogVisible = ref(false)
const salesScriptForm = ref({
  customerId: '',
  stage: 'FIRST_CONTACT',
  notes: ''
})

// 处理AI命令
const handleAICommand = (command: string) => {
  switch (command) {
    case 'meeting-summary':
      meetingSummaryDialogVisible.value = true
      break
    case 'extract-tasks':
      extractTasksDialogVisible.value = true
      selectedMessageIds.value = []
      break
    case 'sales-script':
      salesScriptDialogVisible.value = true
      break
    case 'generate-content':
      contentGenerateDialogVisible.value = true
      break
    case 'smart-search':
      // TODO: 打开智能搜索面板
      ElMessage.info('智能搜索功能开发中')
      break
  }
}

// 生成会议总结
const generateMeetingSummary = async () => {
  const conversationId = conversationStore.activeConversationId
  if (!conversationId) {
    ElMessage.warning('请先选择一个会话')
    return
  }

  try {
    generating.value = true
    await aiMessageAPI.requestMeetingSummary(
      conversationId,
      meetingSummaryForm.value.startTime.toISOString(),
      meetingSummaryForm.value.endTime.toISOString()
    )
    ElMessage.success('会议总结已生成')
    meetingSummaryDialogVisible.value = false
  } catch (error: any) {
    ElMessage.error(error.message || '生成失败')
  } finally {
    generating.value = false
  }
}

// 提取任务
const extractTasks = async () => {
  const conversationId = conversationStore.activeConversationId
  if (!conversationId) {
    ElMessage.warning('请先选择一个会话')
    return
  }

  if (selectedMessageIds.value.length === 0) {
    ElMessage.warning('请至少选择一条消息')
    return
  }

  try {
    generating.value = true
    const tasks = await aiMessageAPI.extractTasks(conversationId, selectedMessageIds.value)
    ElMessage.success(`已提取${tasks.length}个任务`)
    extractTasksDialogVisible.value = false
  } catch (error: any) {
    ElMessage.error(error.message || '提取失败')
  } finally {
    generating.value = false
  }
}

// 生成内容
const generateContent = async () => {
  const conversationId = conversationStore.activeConversationId
  if (!conversationId) {
    ElMessage.warning('请先选择一个会话')
    return
  }

  if (!contentGenerateForm.value.keywords.trim()) {
    ElMessage.warning('请输入关键信息')
    return
  }

  try {
    generating.value = true
    await aiMessageAPI.generateContent(
      conversationId,
      contentGenerateForm.value.contentType,
      { keywords: contentGenerateForm.value.keywords }
    )
    ElMessage.success('内容已生成')
    contentGenerateDialogVisible.value = false
  } catch (error: any) {
    ElMessage.error(error.message || '生成失败')
  } finally {
    generating.value = false
  }
}

// 获取销售话术
const getSalesScript = async () => {
  const conversationId = conversationStore.activeConversationId
  if (!conversationId) {
    ElMessage.warning('请先选择一个会话')
    return
  }

  if (!salesScriptForm.value.customerId.trim()) {
    ElMessage.warning('请输入客户ID')
    return
  }

  try {
    generating.value = true
    await aiMessageAPI.getSalesScript(
      conversationId,
      salesScriptForm.value.customerId,
      {
        stage: salesScriptForm.value.stage,
        notes: salesScriptForm.value.notes
      }
    )
    ElMessage.success('话术建议已生成')
    salesScriptDialogVisible.value = false
  } catch (error: any) {
    ElMessage.error(error.message || '获取失败')
  } finally {
    generating.value = false
  }
}
</script>

<style scoped lang="scss">
.ai-assistant-panel {
  .ai-toolbar {
    padding: 10px;
    border-bottom: 1px solid #eee;
  }

  .task-extract-hint {
    margin-bottom: 16px;
  }

  .message-selection {
    max-height: 400px;
    overflow-y: auto;
    
    .message-checkbox-item {
      padding: 8px;
      border-bottom: 1px solid #f0f0f0;

      &:hover {
        background-color: #f5f5f5;
      }

      .message-preview {
        display: flex;
        gap: 8px;

        .sender {
          font-weight: 500;
          color: #409eff;
          flex-shrink: 0;
        }

        .content {
          color: #666;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
      }
    }
  }
}
</style>
